mui.init();
mui.plusReady(function() {
	var storage = plus.storage,
		segmentedControlBtns = [].slice.call(document.querySelectorAll(".mui-control-item")), 
		pullCount = 5,
		currentDepartmentId = "11",
		oldIndex = 0;
	pageRefresh();
	// 绑定切换选项卡时的事件处理函数
	document.getElementById('slider').addEventListener('slide', function(e) {
		var newIndex = e.detail.slideNumber;
		if(oldIndex !== newIndex) {
			oldIndex = newIndex++;
			var item = document.getElementById("item" + newIndex);
			if(item.querySelector(".mui-loading")) {
				showSpinner();
				pageRefresh();
			}
		}
	}, false);
	
	(function($) {
		//阻尼系数
		var deceleration = mui.os.ios?0.003:0.0009;
		$('.mui-scroll-wrapper').scroll({
			bounce: false,
			indicators: true, //是否显示滚动条
			deceleration:deceleration
		});
		$.ready(function() {
			//循环初始化所有下拉刷新，上拉加载。
			$.each(document.querySelectorAll('.mui-slider-group .mui-scroll'), function(index, pullRefreshEl) {
				$(pullRefreshEl).pullToRefresh({
					down: {
						callback: function() {
							var self = this;
							setTimeout(function() {
								var container = self.element.querySelector('.item-content'),
									activeSliderBtn = document.querySelector(".mui-control-item.mui-active"),
									index = segmentedControlBtns.indexOf(activeSliderBtn) + 1,
									item = document.getElementById("item" + index),
									storageKey = "order_item" + index;
								if(plus.networkinfo.getCurrentType() !== 1) {
									pullData(index, pullCount, function(html) {
										if(html) {
											container.innerHTML = html;
											bindLinkNormalTapEvent(item); // 正常联网时可以进入设备详情页
										} else {
											// item.querySelector(".mui-pull-bottom-tips").style.display = "none";
											container.innerHTML = "<p class='no-data'>暂时没有相关数据</p>";
										}
										mui.toast("数据加载完毕！");
										storage.setItem(storageKey, html);
									});
								} else {
									mui.toast("网络好像有点小问题，\r\n请检查网络连接~");
								}
								self.endPullDownToRefresh();
							}, 1000);
						}
					},
					up: {
						callback: function() {
							var self = this;
							setTimeout(function() {
								var container = self.element.querySelector('.item-content'),
									ul = container.querySelector('.mui-table-view'),
									activeSliderBtn = document.querySelector(".mui-control-item.mui-active"),
									index = segmentedControlBtns.indexOf(activeSliderBtn) + 1,
									storageKey = "order_item" + index,
									item = document.getElementById("item" + index);
								if(ul) {
									var childNodes = childNodesCount(ul);
									// 设备列表存在时，直接向列表中追加上拉时拉取获得的数据
									if(plus.networkinfo.getCurrentType() !== 1) {
										pullMoreData(index, pullCount, childNodes, function(html) {
											ul.innerHTML += html;
											bindLinkNormalTapEvent(item);
											
											if(html) {
												var storageData = storage.getItem(storageKey);
												storage.setItem(storageKey, storageData.replace("</ul>", html + "</ul>"));
												mui.toast("数据加载完毕~");
											} else {
												mui.toast("没有更多数据了");
											}
										});
									} else {
										mui.toast("网络好像有点小问题，\r\n请检查网络连接~");
									}
								} else {
									// 如果设备列表不存在，拉取数据，并创建列表，往列表中添加数据
									if(plus.networkinfo.getCurrentType() !== 1) {
										pullData(index, pullCount, function(html) {
											if(html) {
												container.innerHTML = html;
												bindLinkNormalTapEvent(item);
											} else {
												// item.querySelector(".mui-pull-bottom-tips").style.display = "none";
												container.innerHTML = "<p class='no-data'>暂时没有相关数据</p>";
											}
											mui.toast("数据加载完毕！");
											storage.setItem(storageKey, html);
										});
									} else {
										mui.toast("网络好像有点小问题，\r\n请检查网络连接~");
									}
								}
								self.endPullUpToRefresh();
							}, 1000);
						}
					}
				});
			});
		});
	})(mui);
	
	function pageRefresh() {
		var activeSliderBtn = document.querySelector(".mui-control-item.mui-active"),
			index = segmentedControlBtns.indexOf(activeSliderBtn) + 1,
			item = document.getElementById("item" + index);
		
		if (plus.networkinfo.getCurrentType() !== 1) {
			pullData(index, pullCount, function(html) {
				if(html) {
					item.querySelector('.item-content').innerHTML = html;					
					bindLinkNormalTapEvent(item);
				} else {
					// item.querySelector(".mui-pull-bottom-tips").style.display = "none";
					item.querySelector('.item-content').innerHTML = "<p class='no-data'>暂时没有相关数据</p>";
				}
				// alert("order_item" + index);
				// 更新本地存储的数据
				storage.setItem("order_item" + index, html);
			});
		} else {
			var storageData = storage.getItem("order_item" + index);
			if (storageData) {
				item.querySelector('.item-content').innerHTML = storageData;
				bindLinkOfflineTapEvent(item);
			} else {
				item.querySelector(".item-content").innerHTML = "<div class='network-error'><p><span class='network-error-icon'><i class='fa fa-exclamation-circle' aria-hidden='true'></i></span></p><p>连接超时</p></div>";
				mui.toast("网络好像有点小问题，\r\n请检查网络连接~");
			}
		}
	}
	
	// 显示加载时旋转图标
	function showSpinner() {
		var activeSliderBtn = document.querySelector(".mui-control-item.mui-active"),
			index = segmentedControlBtns.indexOf(activeSliderBtn) + 1,
			item = document.getElementById("item" + index),
			spinner = '<div class="mui-loading"><div class="mui-spinner"></div></div>';
		if(!item.querySelector('.mui-loading')) {
			item.querySelector(".item-content").innerHTML = spinner;
		}
	}
})

/*
 * 功能：拉取设备列表数据
 * 参数含义：
 * subType：指定要拉取某个子选项卡下包含的数据
 * count：指定拉取条目的最大数目
 * callback：回调，可以接收获取到的HTML字符串作为参数
 * 
 * */
function pullData(subType, count, callback) {
	var urlPrefix = "https://bird.ioliu.cn/v1?url=";
	mui.ajax(urlPrefix + "http://hospital.xiaoweicanting.com/factory.php?m=App&c=orders&a=getOrders&factoryid=1&uid=3&token=dfaf&skip=0&hospitalid=10&departmentid=11&limit=" + count + "&state=" + subType, {
		async: true,
		type: "GET",
		dataType: "json",
		success: function(data, textStatus) {
			if(textStatus === "success") {
				data = data.data;
				var length = data.length, html;
				if(length) {
					html = '<ul class="mui-table-view">';
					for(var i = 0; i < length; i++) {
						html += getALiHTML(data[i], subType > 1);
					}
					html += '</ul>';
				}
				callback(html);
			}
		}
	});
}

/*
 
 * 功能：专门用于在用户上拉列表且列表存在时向后台拉取更多数据
 * subType：指定要拉取某个子选项卡下包含的数据
 * currentCount：当前列表中包含的条目数量
 * pullcount：指定每次加载的条目数量
 * callback：回调，可以接收一个表示是否还有更多数据的布尔值done以及获取到的HTML字符串作为参数
 * 特别指出的是，回调函数接收的参数html如果为0，表示当前选项卡之下已经没有任何数据，需要对当前列表进行清空；
 * 如果html为空字符串，则表示当前列表下没有更多数据，不需要添加更多的数据。
 * */
function pullMoreData(subType, pullCount, currentCount, callback) {
	var urlPrefix = "https://bird.ioliu.cn/v1?url=";
	mui.ajax(urlPrefix + "http://hospital.xiaoweicanting.com/factory.php?m=App&c=orders&a=getOrders&factoryid=1&uid=3&token=dfaf&hospitalid=10&departmentid=11&skip=" + currentCount + "&limit=" + pullCount + "&state=" + subType, {
		async: true,
		type: "GET",
		dataType: "json",
		success: function(data, textStatus) {
			if(textStatus === "success") {
				var data = data.data,
					length = data.length, html = "";
				if(length) {
					for(var i = 0; i < length; i++) {
						html += getALiHTML(data[i], subType > 1);
					}
				}
				callback(html);
			}
		}
	});
}

function getALiHTML(data, addEngineer) {
	var rootPath = "http://hospital.xiaoweicanting.com/";
	// 用户头像为空时，自动设置为 汉字取末尾，英文取首字母大写
	var doctorName = data.addname.split(""), doctorShortName;
    if (isChinese(data.addname)) {
        doctorShortName = doctorName[doctorName.length - 1];
    } else {
        doctorShortName = doctorName[0].toUpperCase();
    }
    
    if(addEngineer) {
    		var engineerName = data.workdername.split(""), engineerShortName;
        if (isChinese(data.workdername)) {
            engineerShortName = engineerName[engineerName.length - 1];
        } else {
            engineerShortName = engineerName[0].toUpperCase();
        }
    }
    
    // 加急标志设置 faultlevel 1->加急 2->紧急 3->超急
    var faultlevel = "", faultClass = "";
    if (data.faultlevel == 1) {
        faultlevel = "加急";
        faultClass = "jiaji-situation";
    } else if (data.faultlevel == 2) {
        faultlevel = "紧急";
        faultClass = "jinji-situation";
    } else if (data.faultlevel == 3) {
        faultlevel = "超急";
        faultClass = "chaoji-situation";
    }
    
    var engineerInfo = addEngineer ? 
                    		'<div class="engineer-info">' + 
                    			'<p class="text-border ' + faultClass + '">' + faultlevel + '</p>' + 
                    			(
                    				data.workderuimg ?
                    				"<img src=\"../../images/test/timg.jpeg\" id=\"engineer-display\" data-src=\"" + rootPath + data.workderuimg + "\" onload=\"load(this)\" />" 
                    				: 
                    				"<span class=\"circle-name engineer-circle-name\">" + engineerShortName + "</span>"
                    			) +
							'<p class="engineer-name">' + data.workdername + '</p>' + 
							'<p class="engineer-role">' + data.workderrole + '</p>' + 
						'</div>'
                    		: 
                    		'<div class="engineer-info">' + 
                    			'<span class="text-border ' + faultClass + '">' + faultlevel + '</span>' + 
                    		'</div>';

    var orderInfo = '<div class="list-item-content">' + 
						'<p class="doctor-info">' + 
							(
                    				data.adduimg ?
                    				"<img src=\"../../images/test/timg.jpeg\" data-src=\"" + rootPath + data.adduimg + "\" onload=\"load(this)\" />" 
                    				: 
                    				"<span class=\"circle-name doctor-circle-name\">" + doctorShortName + "</span>"
                    			) +
							'<span class="doctor-name">' + data.addname + '</span>' + 
						'</p>' + 
						'<p class="hospital-department">西京医院-' + data.departmentname + '</p>' + 
						'<h5 class="order-title">' + data.title + '</h5>' + 
						'<p class="order-content">' + data.content + '</p>' + 
						'<p class="add-time">' + data.addtime + '</p>' + 
					'</div>';
	return '<li class="mui-table-view-cell">' + 
				'<a href="javascript:;" data-order=\'{"id":' + data.sid + ',"state":' + data.w_order_state + ',"factoryId":' + data.factoryid + ',"workerId":' + data.workderid + ',"workername":"' + data.workdername + '"}\'>' + 
					engineerInfo + 
					orderInfo + 
				'</a>' + 
			'</li>';
}

function isChinese(text) {
    var reg = new RegExp("[\\u4E00-\\u9FFF]+", "g");
    if (reg.test(text)) {
        return true;
    } else {
        return false;
    }
}

function bindLinkNormalTapEvent(item) {
	[].slice.call(item.querySelectorAll("a")).forEach(function(v) {
		v.addEventListener("tap", function() {
			turnToOrderDetail(JSON.parse(this.getAttribute("data-order")));
		}, false);
	});
}

function bindLinkOfflineTapEvent(item) {
	[].slice.call(item.querySelectorAll("a")).forEach(function(v) {
		v.addEventListener("tap", function() {
			mui.toast("网络好像有点小问题，\r\n请检查网络连接~");
		}, false);
	});
}

// 计算给定节点下包含的元素节点个数
function childNodesCount(node) {
	var count = 0, childNodes = node.childNodes;
	for(var i = 0, len = childNodes.length; i < len; i++) {
		if (childNodes[i].nodeType === 1) {
			count++;
		}
	}
	return count;
}
/*
 
 * w_order_state:
 * 1：管理员未分配任务
 * 2：管理员已分配任务
 * 3：工程师已接受任务
 * 4：工程师已修好
 * 5：医院端已确认
 * 
 * */
function turnToOrderDetail(order) {
	mui.openWindow({
		url: "order_detail.html",
		extras: {
			order: order
		},
		styles: {
			scrollIndicator: "none"
		}
	});
}